﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WorkBasket.Data.Entities;
using WorkBasket.Data.Repository;
using WorkBasket.Infrastructure;
using WorkBasket.Models;
using WorkBasket.Api;
using System.Web.Script.Serialization;
using WorkBasket.Areas.Design.Models;

namespace WorkBasket.Controllers.Api
{


    [Authorize]
    public class FormController : ApiController
    {

        private SOC soc = new SOC(new MyContext());


        [Route("api/Form/GetByParentKey/{WorkflowID}")]
        [HttpGet]
        public IHttpActionResult GetByParentKey(int WorkflowID)
        {
            return Json( soc.Forms.Where(c => c.WorkflowID == WorkflowID));
        }


        [Route("api/Form/GetControlData/{ControlName}")]
        [HttpGet]
        public IHttpActionResult GetControlData(string ControlName)
        {
            foreach (IControl ctl in ExtensionsHost.Extensions.Controls)
            {

                JavaScriptSerializer serializer = new JavaScriptSerializer(); //creating serializer instance of JavaScriptSerializer class

                //first way
                
                if(ctl.GetType().FullName==ControlName.Replace("_","."))
                {
                    string json = serializer.Serialize((object)ctl.Properties);
                    var ctlJson = new CtlJson();
                    ctlJson.ControlName = ctl.ControlName;
                    ctlJson.FullName = ctl.GetType().FullName;
                    ctlJson.ToolBoxIcon = ctl.ToolBoxIcon;
                    ctlJson.Properties = json;
                    

                    return Json(ctlJson);
                }
            }
            return NotFound();
        }

        [HttpPost]
        [Route("api/form/save")]
        public IHttpActionResult Post([FromBody] Form value)
        {
            try
            {
                if (value.FormID == 0)
                {
                    soc.Forms.Add(value);
                }
                else
                {
                    soc.Forms.Update(value);
                }

                soc.CommitChanges();
                return Json(new DataReturn(value.FormName + " Saved", value));
            }
            catch (Exception e)
            {
                return new System.Web.Http.Results.ExceptionResult(e, this);
            }
        }

        


    }
}
